/*
 * @Author: 飞越疯人院 353362604@qq.com
 * @Date: 2022-09-28 15:12:35
 * @LastEditors: NaN 353362604@qq.com
 * @LastEditTime: 2023-01-15 10:25:49
 * @FilePath: \adminstration\src\Common\Router\DiyList\WeChatSetUp.jsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置
 * 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import './Scss/WeChatSetUp.scss'
import { useLocalStorageState, useRequest } from 'ahooks'
import { ICON } from '../../../Configure/Icon'
import { Divider, Input, Select, Tooltip, Button, Spin, message } from 'antd'
import { useState } from 'react'
import { Http } from '../../../Api'
import { useEffect } from 'react'
import { MenuMapping, BottomNav, WeChatTheme, WechatLogo } from '../../../Configure/CommonParameter'
import { DeleteOutlined } from '@ant-design/icons'
import GridLayout from 'react-grid-layout'

const { Option } = Select

const NotNavList = [
    'd9b18d92-2f3d-41c8-a82a-0777bb90be80',
    '78f831a5-b4a5-4198-b59f-a6a319567ab9',
    'e673337b-9fd0-4a90-8dc6-3dab5a3fb18c',
]

const removeNotNav = (arr, key) => {
    for (let v of key) arr = arr.filter(item => item.uuid !== v)
    return arr
}

export const WeChatSetUp = () => {
    const [ModifyState, setModifyState] = useState()
    const [Uuid, setUuid] = useState()
    const [layout, setLayout] = useState([])
    const [ClientData] = useLocalStorageState('ClientData')
    const [projectName] = Object.values(ClientData.project)
    const [Title, setTitle] = useState(projectName)
    const [Theme, setTheme] = useState('拂晓')
    const [Logo, setLogo] = useState()
    const [Order, setOrder] = useState('1')
    const [WeChatMenuList, setWeChatMenuList] = useState([])
    const [loading, setLoading] = useState(true)
    const { runAsync: getWeChatList } = useRequest(Http, {
        manual: true,
        onSuccess: ({ list }) => setWeChatMenuList(removeNotNav(list, NotNavList)),
    })

    const { runAsync: getSmallProgramConfig } = useRequest(Http, {
        manual: true,
        onSuccess: list => {
            setLoading(false)
            if (list.length !== 0) {
                let [{ uuid, tableName, theme, order, menus, logo }] = list
                setLogo(logo)
                setTitle(tableName)
                setTheme(theme)
                setOrder(order)
                setLayout(JSON.parse(menus))
                setModifyState(uuid)
            }
        },
    })

    const { runAsync } = useRequest(Http, { manual: true })

    useEffect(() => {
        getWeChatList({ url: 'getWechatMenu' })
        getSmallProgramConfig({ url: 'getSmallProgramConfig' })
    }, [getWeChatList, getSmallProgramConfig])

    const SubmitSetUp = () => {
        setLoading(true)
        let data = {
            uuid: ModifyState,
            tableName: Title,
            theme: Theme,
            order: Order,
            logo: Logo,
            login: '0',
            menus: JSON.stringify(layout),
        }
        if (ModifyState) {
            runAsync({ url: 'putSmallProgramConfig', data, path: [ModifyState] })
                .then(() => {
                    message.success('修改配置成功!')
                    setLoading(false)
                })
                .catch(() => {
                    message.error('修改配置失败!')
                    setLoading(false)
                })
        } else {
            runAsync({ url: 'posSmallProgramConfig', data })
                .then(() => {
                    message.success('新增配置成功!')
                    setLoading(false)
                })
                .catch(() => {
                    message.error('新增配置失败!')
                    setLoading(false)
                })
        }
    }

    return (
        <div className="WeChatSetUp">
            <Spin spinning={loading}>
                <div className="Basics">
                    <Divider orientation="left">基础配置</Divider>
                    <div className="input">
                        <div>标题 : </div>
                        <Input value={Title} onChange={({ target }) => setTitle(target.value)} />
                    </div>
                    <div className="input">
                        <div>主题 : </div>
                        <Select value={Theme} style={{ width: '100%' }} onChange={e => setTheme(e)}>
                            {Object.keys(WeChatTheme).map((item, index) => (
                                <Option key={`WeChatSetUpTheme${index}`} value={WeChatTheme[item]}>
                                    {item}
                                </Option>
                            ))}
                        </Select>
                    </div>
                    <div className="input">
                        <div>LOGO : </div>
                        <Select value={Logo} style={{ width: '100%' }} onChange={e => setLogo(e)}>
                            {Object.keys(WechatLogo).map((item, index) => (
                                <Option key={`WeChatSetUpLogo${index}`} value={WechatLogo[item]}>
                                    {item}
                                </Option>
                            ))}
                        </Select>
                    </div>
                    <div className="input">
                        <div>下单 : </div>
                        <Select defaultValue={Order} style={{ width: '100%' }} onChange={e => setOrder(e)}>
                            <Option value="0">关闭</Option>
                            <Option value="1">开启</Option>
                        </Select>
                    </div>
                    <Button block size="large" type="primary" onClick={SubmitSetUp}>
                        保存配置信息
                    </Button>
                </div>
                <div className="preview">
                    <div className="WeChatBox">
                        <div className="top" style={{ background: `rgb(${Theme})`, color: 'white' }}>
                            <div className="top">智慧工地管理云平台</div>
                            <div className="name">
                                <div>{Title}</div>
                                <img src={Logo} alt="" />
                            </div>
                        </div>
                        <div className="menu">
                            {Order ? (
                                <div
                                    className="OrderBtn"
                                    style={{
                                        background: `linear-gradient(90deg, rgba(${Theme},0.85) , rgb(${Theme}) )`,
                                        boxShadow: `0px 0px 8px 0px rgba(${Theme}, 0.5)`,
                                    }}
                                >
                                    <img
                                        src="https://image.ljkjkf.com/intellisiteSystem_TieKe/Applets/Home_Top.png"
                                        alt=""
                                    />
                                    <div>巡检下单</div>
                                </div>
                            ) : (
                                ''
                            )}
                            <div className="box" style={{ height: Order ? 'calc(100% - 59px)' : '100%' }}>
                                <GridLayout
                                    className="layout"
                                    layout={layout}
                                    margin={[15, 15]}
                                    cols={2}
                                    rowHeight={100}
                                    width={375}
                                    isDroppable={true}
                                    isResizable={true}
                                    onDrop={e => {
                                        let NewBox = e.findIndex(v => v.i === '__dropping-elem__')
                                        e[NewBox] = { ...e[NewBox], i: Uuid, maxW: 2, maxH: 2 }
                                        setLayout(e)
                                        setUuid()
                                    }}
                                    onResizeStop={e => setLayout(e)}
                                    onDragStop={e => setLayout(e)}
                                >
                                    {layout.map(({ i }) => (
                                        <div className="MenuItem" key={i} style={{ background: '#f00' }}>
                                            <img src={MenuMapping[i].back} alt="" />
                                            <Tooltip
                                                title="删除菜单"
                                                onClick={() => setLayout(layout.filter(v => v.i !== i))}
                                            >
                                                <DeleteOutlined className="MenuDelete" />
                                            </Tooltip>

                                            <div className="MenuBox" style={{ background: `rgba(${Theme},0.6)` }}>
                                                {ICON[MenuMapping[i].icon]}
                                                <div>{MenuMapping[i].name}</div>
                                            </div>
                                        </div>
                                    ))}
                                </GridLayout>
                            </div>
                        </div>
                        <div className="bottom">
                            {BottomNav.map((item, index) => (
                                <div className="icon" key={`bottomNav${index}`}>
                                    {ICON[item.icon]}
                                    <div style={index === 0 ? { color: `rgb(${Theme})` } : { color: '#262626' }}>
                                        {item.name}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
                <div className="Menu">
                    <Divider orientation="left">菜单配置</Divider>
                    <div className="MenuList">
                        {/* {console.log(WeChatMenuList)} */}
                        {WeChatMenuList.map(({ uuid, tableName }) => {
                            if (layout.findIndex(v => v.i === uuid) !== -1) return false
                            return (
                                <div
                                    key={`WeChatMenuList${uuid}`}
                                    className="MenuItem"
                                    draggable={true}
                                    onDragStart={() => setUuid(uuid)}
                                >
                                    <img src={MenuMapping[uuid]?.back} alt="" />
                                    <div style={{ background: `rgba(${Theme},0.6)` }}>
                                        {ICON[MenuMapping[uuid]?.icon]}
                                        <div>{MenuMapping[uuid]?.name}</div>
                                    </div>
                                </div>
                            )
                        })}
                    </div>
                </div>
            </Spin>
        </div>
    )
}
